package cn.itcast.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Role;
import cn.itcast.service.RoleService;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController {
    @Reference
    private RoleService roleService;

    @PreAuthorize("hasAuthority('ROLE_EDIT')")
    @PutMapping
    public ResponseEntity<Result> edit(@RequestParam("permissionIds") List<Integer> permissionIds,
                                       @RequestParam("menuIds") List<Integer> menuIds,
                                       @RequestBody Role role) {
        Result result = new Result();
        try {
            Boolean flag = roleService.edit(permissionIds,menuIds,role);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.EDIT_ROLE_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.EDIT_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.EDIT_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }


   // @Secured({"ROLE_DELETE"})
    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> delete(@PathVariable Integer id) {
        Result result = new Result();
        try {
            Boolean flag = roleService.delete(id);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.DELETE_ROLE_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.DELETE_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.DELETE_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }


    /**
     * 新建角色
     *
     * @return
     */
    @PreAuthorize("hasAuthority('ROLE_ADD')")
    @PostMapping
    public ResponseEntity<Result> saveRole(@RequestParam("permissionIds") List<Integer> permissionIds,
                                           @RequestParam("menuIds") List<Integer> menuIds,
                                           @RequestBody Role role) {
        Result result = new Result();
        try {
            Boolean flag = roleService.save(permissionIds, menuIds, role);
            if (flag) {
                result.setFlag(true);
                result.setMessage(MessageConstant.ADD_ROLE_SUCCESS);
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error(MessageConstant.ADD_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.ADD_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }

    /**
     * 查询
     *
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @GetMapping("/page")
    public ResponseEntity<Result> findByPage(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
                                             @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                             @RequestParam(value = "queryString", required = false) String queryString) {
        Result result = new Result();
        try {
            PageResult pageResult = roleService.findByPage(currentPage, pageSize, queryString);
            if (ObjectUtil.isNotEmpty(pageResult)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_ROLE_SUCCESS);
                result.setData(pageResult);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Result> findById(@PathVariable Integer id) {
        Result result = new Result();
        try {
            Role role = roleService.findById(id);
            if (ObjectUtil.isNotEmpty(role)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_ROLE_SUCCESS);
                result.setData(role);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }

    /**
     * 角色关联菜单
     * @param id
     * @return
     */
    @GetMapping("/{id}/menu")
    public ResponseEntity<Result> findMenuIdsByRoleId(@PathVariable Integer id) {
        Result result = new Result();
        try {
            List<Integer> menuIds = roleService.findMenuIdsByRoleId(id);

            result.setFlag(true);
            result.setMessage(MessageConstant.QUERY_MENU_SUCCESS);
            result.setData(menuIds);
            return ResponseEntity.ok(result);


        } catch (Exception e) {
            log.error(MessageConstant.QUERY_MENU_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_MENU_FAIL);
        return ResponseEntity.ok(result);
    }

    /**
     * 角色关联权限
     * @param id
     * @return
     */
    @GetMapping("/{id}/permission")
    public ResponseEntity<Result> findPermissionIdsByRoleId(@PathVariable Integer id) {
        Result result = new Result();
        try {
            List<Integer> permissionIds = roleService.findPermissionIdsByRoleId(id);

            result.setFlag(true);
            result.setMessage(MessageConstant.QUERY_PERMISSION_SUCCESS);
            result.setData(permissionIds);
            return ResponseEntity.ok(result);


        } catch (Exception e) {
            log.error(MessageConstant.QUERY_PERMISSION_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_PERMISSION_FAIL);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/all")
    public ResponseEntity<Result> findAll() {
        Result result = new Result();
        try {
            List<Role> roles = roleService.findAll();
            if (ObjectUtil.isNotEmpty(roles)) {
                result.setFlag(true);
                result.setMessage(MessageConstant.QUERY_ROLE_SUCCESS);
                result.setData(roles);
                return ResponseEntity.ok(result);
            }

        } catch (Exception e) {
            log.error(MessageConstant.QUERY_ROLE_FAIL, e);
        }
        result.setFlag(false);
        result.setMessage(MessageConstant.QUERY_ROLE_FAIL);
        return ResponseEntity.ok(result);
    }
}
